<?php
/*
 * UI Generator
 * 用于jquery-ui界面构建
 * 
 * @since 
 *      1.3 2014-7-31 by sutroon 新增自定义模板功能
 *      1.2 2014-7-29 by sutroon 新增表单参数代码生成功能
 *      1.1 2014-7-25 by sutroon 新增数据库登录功能
 *      1.0 2014-7-21 by sutroon
 * @remark 20147-2-21开发至2014-7-24完工,期间攻克了随机数模板和更有挑战的多字段递增函数模板,最后终于完成了自己以前两次都未完成的代码模板生成器开发.感谢自己为自己又完成了一个小心愿!
 */
require 'Inc/incDbHead.php';

/**
 * 更新字段表
 * @since 1.0 2014-7-31 by sutroon
 */
function update_tsofields() {
    $result = mysql_query('show tables;');
    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        $result2 = mysql_query('SHOW FULL FIELDS FROM ' . $row[0]);
        $sql = 'insert into tsofields(`table`,`field`,`dataType`,`comment`,`desc`) values ';
        while ($row2 = mysql_fetch_assoc($result2)) {
            $sql.="('" . $row[0] . "','" . $row2['Field'] . "','" . $row2["Type"] . "','" . $row2["Comment"] . "',''),";
        }
        mysql_query(rtrim($sql, ',')) or die(mysql_error());
    }
}

if ($action == 'createtable') {
    create_tables();
    update_tsofields();
    die('success');
}
if ($action == 'showconnection') {
    $r = mysql_query("SELECT DATABASE()") or die(mysql_error());
    die('DB:' . mysql_result($r, 0));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>SoUIGenerator</title>
        <meta charset="UTF-8">
        <style type='text/css'>
            body { font-size:12px;}
            table{width:100%; border: solid 1px #CCC; border-left:none; border-bottom: none;}
            th:first-child{width:30px;}
            .th-field {width:500px;}
            th, td { padding: 5px; border:solid 1px #CCC; border-right: none; border-top: none;}
            tr.tr-alt { background-color: #efefef;}
            a { text-decoration: none;}
            .tab { padding: 10px 0px 5px 0px;}
            .tab a { margin-right:10px;}
            .tab .cur { text-decoration: underline;}
            .panel-left {width:800px; height:450px; overflow:scroll;float:left;}
            .panel-right{width:800px; height:450px; float:left;}
            .panel-right textarea {width:800px; height:450px;}
        </style>
        <script type="text/javascript" src="/Public/Script/jquery-1.11.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('.panel-left, .panel-right textarea').height($(document).height() - 90);
                // 构建器标签栏切换
                $('.tab a').click(function() {
                    switch_tab($(this));
                    return false;
                });
                $('#connform a').click(function() {
                    $(this).prev().val('');
                    return false;
                })

                // 字段全部勾选并生成 2014-7-29 by sutroon
                $('.chkAll').click(function() {
                    var chk = $(this).prop('checked');
                    var val = $(this).val();
                    if (val == 'params') {
                        $('#' + val + '-builder td:nth-child(3) input').prop('checked', chk);
                    } else {
                        $('#' + val + '-builder td:nth-child(2) input').prop('checked', chk);
                    }
                    if (chk) {
                        switch (val) {
                            case 'form':
                                generate_form();
                                break;
                            case 'table':
                                generate_table();
                                break;
                            case 'data':
                                generate_data();
                                break;
                            case 'params':
                                generate_params();
                                break;
                        }
                    } else {
                        $('#' + val + '-code-panel').val('');
                    }
                })

                // 设置模板按钮
                $('.lnksetting').click(function() {
                    $(this).parent().find('.tpl').toggle();
                })

                // 字段是否启用勾选
                $('#form-builder input[name="field"]').click(function() {
                    generate_form();
                });
                $('#table-builder input[name="field"]').click(function() {
                    generate_table();
                });
                $('#data-builder input[name="field"]').click(function() {
                    generate_data();
                });
                $('#params-builder input[name="type"]').click(function() {
                    generate_params();
                });
                // 表单UI控件类型过滤
                $('#form-builder select[name="type"]').change(function() {
                    var $this = $(this);
                    var $tr = $this.parentsUntil('tr').parent();
                    formbuilder_typechange($this.val(), $tr);
                });
                // 数据UI控件类型过滤
                $('#data-builder select[name="type"]').change(function() {
                    var $this = $(this);
                    var $tr = $this.parentsUntil('tr').parent();
                    databuilder_typechange($this.val(), $tr);
                });
            })
        </script>
    </head>
    <body>
        <?php
        // 显示数据库登录表单
        if (!$conn_info) {
            echoDbLoginForm();
        }
        // 全局菜单
        include 'Inc/incMenu.php';

        $table = isset($_GET['table']) ? $_GET['table'] : ''; // 获取当前选中的数据表名称
        // 显示所有数据表的下拉框
        $result = mysql_query('show tables;'); // 读取所有数据表 
        // 生成数据表下拉控件
        $str = '<div><select id="table-name" onchange="location.href=\'?table=\'+this.value"><option>请选择</option>';
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            $str.='<option value="' . $row[0] . '"' . ($table && $row[0] == $table ? ' selected="selected"' : '') . '>' . $row[0] . '</option>';
        }
        $str.= '" /> <a href="../SoProjectManager.php" target="_blank">[ProjMgr]</a></div>';
        echo $str;

        // 如果有选中表则开始生成构建器界面
        if ($table) {
            $result = mysql_query('SHOW FULL FIELDS FROM ' . $table); // 查询包含注释的字段定义
            $arr = null;
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $arr[] = $row;
            }

            // 生成构建器标签菜单
            echo '<div class="tab"><a href="form" class="cur">Form Builder</a><a href="table">Table Builder</a><a href="params">Params Builder</a><a href="data">Data Builder</a></div>';

            // 显示表单UI构建器
            $str = '<div id="form-builder" class="tabcontent">';
            $str.='<a href="#" class="lnksetting">==设置==</a> <input type="checkbox" class="chkAll" value="form" />全选<br />';
            $str.='<fieldset class="tpl" style="display:none"><legend>模板设置</legend>';
            $str.='Head:<br /><textarea cols="108" rows="6" name="tplhd"><div class="panel">' . PHP_EOL . '<h3>编辑</h3>' . PHP_EOL . '<form action="?s=Model/item_edit_save" method="post">' . PHP_EOL . '<ul>' . PHP_EOL . '</textarea><br />';
            $str.='Field:<br /><textarea cols="108" rows="5" name="tplfield"><li>' . PHP_EOL . '<label>{comment}：</label>' . PHP_EOL . '{control}' . PHP_EOL . '</li>' . PHP_EOL . '</textarea><br />';
            $str.='Foot:<br /><textarea cols="108" rows="5" name="tplft"></ul>' . PHP_EOL . '</form>' . PHP_EOL . '</div>' . PHP_EOL . '</textarea>';
            $str.='</fieldset>';
            $str.='<div class="panel-left">';
            $str.='<table cellspacing="0"><tr><th>序号</th><th class="th-field">字段定义</th><th>操作</th></tr>';
            $i = 0;
            foreach ($arr as $row) {
                $style = ($i % 2 == 0) ? ' class="tr-alt"' : '';
                $str.='<tr' . $style . '><td>' . $i . '</td><td>' . get_td_field($row) . '</td><td>';
                $str.='<div>控件类型：<select name="type"><option value="text">文本输入框</option><option value="hidden">隐藏域</option><option value="file">文件域</option><option value="textarea">多行文本域</option><option value="editor">编辑器</option><option value="select">下拉框</option><option value="radio">单选组</option><option value="checkbox">复选框</option><option value="password">密码框</option><option value="timepicker">时间选择器</option><option value="datepicker">日期选择器</option></select></div>';
                $str.='<div>是否必填：<input type="checkbox" name="required" title="表单域是否是必填项" /></div>';
                $str.='<div>标签名称：<input type="text" name="label" value="' . $row['Comment'] . '" title="如：名称、值等" /></div>';
                $str.='<div>值变量名：<input type="text" name="valuevar" value="$data" title="值格式：{$data.field},如果变量不是以$开头视为固定值" /></div>';
                $str.='<div style="display:none">下拉框数据源：<input type="text" name="jsonsource" value="?s=Model/get_json.html" size="42" /><a href="###" onclick="$(this).prev().val(\'\');return false;">[x]</a></div>';
                $str.='<div style="display:none">值范围：<input type="text" name="groupdata" placeholder="如:0=正常&!1=禁用 (值的前面加符号[!]表示选中)" size="48" title="格式为：value1=text1&value2=text2,值的前面加符号[!]表示选中" /><a href="###" onclick="$(this).prev().val(\'\');return false;">[x]</a></div>';
                $str.='</td></tr>';
                $i++;
            }
            $str.='</table></div>';
            $str.='<div class="panel-right"><textarea id="form-code-panel" style="width:800px; height:450px;"></textarea></div><i style="clear:both"></i>';
            $str.='</div>';
            echo $str;

            // 显示列表(表格)UI构建器
            $str = '<div id="table-builder" class="tabcontent" style="display:none; height:450px;">';
            $str.='<a href="#" class="lnksetting">==设置==</a> <input type="checkbox" class="chkAll" value="table" />全选 <input type="checkbox" id="chkBatch" />允许批量选择 <input type="checkbox" id="chkOptCol" />生成操作列<br />';
            $str.='<fieldset class="tpl" style="display:none"><legend>模板设置</legend>';
            $str.='<input type="checkbox" name="istable" value="1" checked="checked" />表格(Table) <input type="checkbox" name="isstrict" value="1" checked="checked" />规范的表格格式(包含&lt;thead/&gt;,&lt;tbody/&gt;标签)';
            $str.='Head:<br /><textarea cols="108" rows="6" name="tplhd"><table>' . PHP_EOL . '</textarea><br />';
            $str.='Th:<br /><textarea cols="108" rows="3" name="tplth"><th>{comment}</th></textarea><br />';
            $str.='Loop:<br /><textarea cols="108" rows="3" name="tplloop"><foreach name="list" item="vo" >{rows}</foreach></textarea><br />';
            $str.='Td:<br /><textarea cols="108" rows="3" name="tpltd"><td>{$vo.{field}}</td></textarea><br />';
            $str.='Foot:<br /><textarea cols="108" rows="5" name="tplft">' . PHP_EOL . '</table>' . PHP_EOL . '{$page}</textarea>';
            $str.='</fieldset>';
            $str.='<div class="panel-left">';
            $str.='<table cellspacing="0"><tr><th>序号</th><th class="th-field">字段定义</th><th>操作</th></tr>';
            $i = 0;
            foreach ($arr as $row) {
                $style = ($i % 2 == 0) ? ' class="tr-alt"' : '';
                $str.='<tr' . $style . '><td>' . $i . '</td><td>' . get_td_field($row) . '</td><td>';
                $str.='<div>标题名称：<input type="text" name="label" value="' . $row['Comment'] . '" title="如：名称、值等" /></div>';
                $str.='<div>值函数：<input type="text" name="valuevar" title="值函数,如：{$vo.state|get_state_text=user,###}" /></div>';
                $str.='</td></tr>';
                $i++;
            }
            $str.='</table></div>';
            $str.='<div class="panel-right"><textarea id="table-code-panel"></textarea></div><i style="clear:both"></i>';
            $str.='</div>';
            echo $str;

            // 显示数据写入UI构建器
            $str = '<div id="data-builder" class="tabcontent" style="display:none; height:450px;">';
            $str.='<input type="checkbox" class="chkAll" value="data" />全选 生成数量：<input type="text" id="num" value="10" size="4" /><br />';
            $str.='<div class="panel-left"><table cellspacing="0"><tr><th>序号</th><th class="th-field">字段定义</th><th>操作</th></tr>';
            $i = 0;
            foreach ($arr as $row) {
                $style = ($i % 2 == 0) ? ' class="tr-alt"' : '';
                $str.='<tr' . $style . '><td>' . $i . '</td><td>' . get_td_field($row) . '</td><td>';
                $str.='<div>值类型：<select name="type"><option value="static">固定值</option><option value="increment">递增值</option><option value="random">随机数</option></select></div>';
                $str.='<div>值：<input type="text" name="valuevar" title="随机数格式：最小值<最大值,或1,2,3;\n" value="' . $row['Default'] . '" /></div>';
                $str.='</td></tr>';
                $i++;
            }
            $str.='</table></div>';
            $str.='<div class="panel-right"><textarea id="data-code-panel"></textarea></div><i style="clear:both"></i>';
            $str.='</div>';
            echo $str;

            // 显示表单参数构建器 2014-7-29 by sutroon
            $str = '<div id="params-builder" class="tabcontent" style="display:none; height:450px;">';
            $str.='<input type="checkbox" class="chkAll" value="params" />全选<br />';
            $str.='<div class="panel-left">';
            $str.='<table cellspacing="0"><tr><th>序号</th><th class="th-field">字段定义</th><th>操作</th></tr>';
            $i = 0;
            foreach ($arr as $row) {
                $style = ($i % 2 == 0) ? ' class="tr-alt"' : '';
                $str.='<tr' . $style . '><td>' . $i . '</td><td>' . get_td_field($row, false) . '</td><td>';
                $str.='<input type="checkbox" name="type" value="addParam" />addParam <input type="checkbox" name="type" value="addData" />addData';
                $str.='<input type="hidden" name="datatype" value="' . $row['Type'] . '" /><input type="hidden" name="comment" value="' . $row['Comment'] . '" />';
                $str.='</td></tr>';
                $i++;
            }
            $str.='</table></div>';
            $str.='<div class="panel-right"><textarea id="params-code-panel"></textarea></div><i style="clear:both"></i>';
            $str.='</div>';
            echo $str;
        }

        // 释放资源
        mysql_free_result($result);
        unset($db);
        ?>

        <script type='text/javascript' title="页面控制方法">
            /**
             * 构建表单UI
             * @returns {void}
             * @since 1.0 2014-7-21 by sutroon
             */
            function generate_form() {
                var table = $('#table-name').val();
                var str = '', $tr, scripts = '', formtype = '', hidinputs = '', ctrl = '';
                var field = '', label = '', type = '', valuevar = '', required = '', jsonsource = '', groupdata = '';
                var $tpl = $('#form-builder .tpl');
                var tplhd = $tpl.find('textarea[name="tplhd"]').val(), tplfield = $tpl.find('textarea[name="tplfield"]').val(), tplft = $tpl.find('textarea[name="tplft"]').val();
                $('#form-builder tr').each(function(i, o) {
                    $tr = $(o);
                    if ($tr.find('input[name="field"]').prop('checked')) {
                        field = $tr.find('input[name="field"]').val();
                        label = $tr.find('input[name="label"]').val();
                        type = $tr.find('select[name="type"]').val();
                        valuevar = $tr.find('input[name="valuevar"]').val();
                        required = $tr.find('input[name="required"]').prop('checked') ? ' required' : '';
                        jsonsource = $tr.find('input[name="jsonsource"]').val();
                        groupdata = $tr.find('input[name="groupdata"]').val();
                        valuevar = (valuevar[0] == '$') ? '{' + valuevar + '.' + field + '}' : valuevar;
                        if (type == 'hidden') {
                            hidinputs += '\n<input type="hidden" name="' + field + '" value="' + valuevar + '" />';
                        } else {
                            switch (type) {
                                case 'text':
                                    ctrl = '<input type="text" name="' + field + '" placeholder="请输入' + label + '" value="' + valuevar + '" title="请输入' + label + '"' + required + ' />';
                                    break;
                                case 'password':
                                    ctrl = '<input type="text" name="' + field + '" placeholder="请输入' + label + '" value="' + valuevar + '" title="请输入' + label + '"' + required + ' />';
                                    if (valuevar) {
                                        scripts += "$('input[name=\"" + field + "\"]').val('" + valuevar + "');";
                                    }
                                    break;
                                case 'file':
                                    formtype = ' enctype="multipart/form-data" ';
                                    ctrl = '<input type="file" name="' + field + '" data-value="' + valuevar + '" />';
                                    break;
                                case 'textarea':
                                    ctrl = '<textarea name="' + field + '" placeholder="请输入' + label + '" title="请输入' + label + '"' + required + '>' + valuevar + '</textarea>';
                                    break;
                                case 'editor':
                                    ctrl = '<textarea name="' + field + '" placeholder="请输入' + label + '" title="请输入' + label + '"' + required + ' class="editor">' + valuevar + '</textarea>';
                                    break;
                                case 'select':
                                    ctrl = '<select name="' + field + '" title="请选择' + label + '"' + required + '>' + generate_group_option(groupdata) + '</select>';
                                    if (jsonsource) {
                                        scripts += "JQUIHelper.load_options('select[name=\"" + field + "\"]', '" + jsonsource + "', '请选择" + label + "','" + valuevar + "');\n";
                                    } else {
                                        if (valuevar) {
                                            scripts += "$('select[name=\"" + field + "\"]').find('option[value=\"" + valuevar + "\"]').prop('selected',true);"
                                        }
                                    }
                                    break;
                                case 'radio':
                                case 'checkbox':
                                    ctrl = generate_group_input(type, groupdata, field, label, required);
                                    if (valuevar) {
                                        scripts += "$('input[name=\"" + field + "\"][value=\"" + valuevar + "\"]').prop('checked',true);"
                                    }
                                    break;
                                case 'timepicker':
                                    ctrl = '<input type="text" name="' + field + '" class="timepicker" value="' + valuevar + '" title="请选择' + label + '"' + required + ' />';
                                    break;
                                case 'datepicker':
                                    ctrl = '<input type="text" name="' + field + '" class="datepicker" value="' + valuevar + '" title="请选择' + label + '"' + required + ' />';
                                    break;
                            }
                            str += tplfield.replace('{comment}', label).replace('{control}', ctrl);
                        }
                    }
                });
                str = (formtype.length > 0 ? tplhd.replace('<form ', '<form ' + formtype) : tplhd) + str;
                str += tplfield.replace(':', '').replace('：', '').replace('{comment}', '&nbsp;').replace('{control}', '<input type="submit" value="保存" /><input type="reset" value="重置" />' + hidinputs);
                str += tplft;
                if (scripts) {
                    str += '\n\n<script type="text/javascript">\n' + scripts + '\n<\/script>';
                }
                $('#form-code-panel').val(str);
            }

            /**
             * 构建列表UI
             * @returns {void}
             * @since 1.0 2014-7-21 by sutroon
             */
            function generate_table() {
                var chkAll = $('#chkBatch').prop('checked');
                var chkOptCol = $('#chkOptCol').prop('checked');
                var str = '<a href="?s=Model/item_edit.html" class="btn-plus btn-icon btn-small">新增</a>\n', strth = '', strtd = '', $tr, valuevar = '', trow = '';
                var field = '', label = '';
                var $tpl = $('#table-builder .tpl');
                var tplhd = $tpl.find('textarea[name="tplhd"]').val();
                var tplth = $tpl.find('textarea[name="tplth"]').val();
                var tpltd = $tpl.find('textarea[name="tpltd"]').val();
                var tplloop = $tpl.find('textarea[name="tplloop"]').val();
                var tplft = $tpl.find('textarea[name="tplft"]').val();
                var isstrict = $tpl.find('input[name="isstrict"]').prop('checked');
                var istable = $tpl.find('input[name="istable"]').prop('checked');
                $('#table-builder tr').each(function(i, o) {
                    $tr = $(o);
                    if ($tr.find('input[name="field"]').prop('checked')) {
                        field = $tr.find('input[name="field"]').val();
                        label = $tr.find('input[name="label"]').val();
                        valuevar = $tr.find('input[name="valuevar"]').val();
                        if (valuevar) {
                            valuevar = '|' + valuevar;
                        }
                        if (tplth.length > 0) {
                            strth += tplth.replace('{comment}', label).replace('{field}', field);
                        }
                        if (tpltd.length > 0) {
                            strtd += tpltd.replace('{field}', field + valuevar);
                        }
                        //strth += '<th>' + label + '</th>';
                        //strtd += '<td>{$vo.' + field + valuevar + '}</td>';
                    }
                });
                if (chkAll) {
                    str += '<form action="?s=Model/index.html" method="post">\n<button type="submit" class="btn-close">批量删除</button>\n';
                }
                str += tplhd;
                if (istable) {
                    if (isstrict) {
                        str += '<thead>\n<tr><th>' + (chkAll ? '<input type="checkbox" />' : '') + '序号</th>' + strth + (chkOptCol ? '<th>操作</th>' : '') + '</tr>\n</thead>\n<tbody>\n';
                    } else {
                        str += '<tr><th>' + (chkAll ? '<input type="checkbox" />' : '') + '序号</th>' + strth + (chkOptCol ? '<th>操作</th>' : '') + '</tr>\n';
                    }
                } else {
                    str += strth + '\n';
                }
                if (istable) {
                    trow += '<tr><td>' + (chkAll ? '<input type="checkbox" name="chk[]" value="{$vo.id}" />' : '') + '{$key}</td>' + strtd;
                    trow += (chkOptCol ? '<td><a href="?s=Model/item_edit/id/{$vo.id}.html">[编辑]</a><a href="#" onclick="JQUIHelper.confirm_redirect(\'?s=Model/item_delete/n/{$vo.extension}.html\')">[删除]</a></td>' : '') + '</tr>\n';
                } else {
                    trow += strtd;
                }
                str += tplloop.replace('{rows}', trow);
                if (istable && isstrict) {
                    str += '</tbody>\n';
                }
                str += tplft;
                if (chkAll) {
                    str += '\n</form>';
                }
                $('#table-code-panel').val(str);
            }

            /**
             * 构建数据语句
             * @returns {void}
             * @since 1.0 2014-7-22 by sutroon
             */
            function generate_data() {
                var num = $('#num').val();
                var str = '', strF = '', strV = '', $tr, field = '', valuevar = '';
                $('#data-builder tr').each(function(i, o) {
                    $tr = $(o);
                    if ($tr.find('input[name="field"]').prop('checked')) {
                        field = $tr.find('input[name="field"]').val();
                        valuevar = $tr.find('input[name="valuevar"]').val();
                        strF += field + ',';
                        strV += '\'' + valuevar + '\',';
                    }
                });
                if (strF.length > 0) {
                    strF = strF.substring(0, strF.length - 1);
                }
                if (strV.length > 0) {
                    strV = strV.substring(0, strV.length - 1);
                }

                inc_dict.clear();
                for (var i = 0; i < num; i++) {
                    str += 'insert into (' + strF + ') values (' + replace_tpl_to_num(strV) + ');\n';
                }
                $('#data-code-panel').val(str);
            }

            /**
             * 构建参数语句
             * @returns {void}
             * @since 1.0 2014-7-29 by sutroon
             */
            function generate_params() {
                var str = '', strP = '', strD = '', $tr, field = '', type = '', comment = '', datatype = '';
                $('#params-builder tr').each(function(i, o) {
                    $tr = $(o);
                    if ($tr.find('input[name="type"]:checked').length > 0) {
                        field = $tr.find('input[name="field"]').val();
                        $tr.find('input[name="type"]:checked').each(function() {
                            switch ($(this).val()) {
                                case 'addParam':
                                    datatype = $tr.find('input[name="datatype"]').val();
                                    comment = $tr.find('input[name="comment"]').val();
                                    datatype = (datatype.indexOf('int') > -1) ? 'number' : 'require';
                                    strP += '$params->addParam(\'' + field + '\', \'' + datatype + '\', \'' + comment + '未填写!\');\n';
                                    break;
                                case 'addData':
                                    strD += '$params->addData(\'' + field + '\', I(\'' + field + '\'));\n';
                                    break;
                            }
                        })
                    }
                });
                if (strP.length > 0) {
                    strP += 'if ($params->hasError()) {\n\t$this->error($params->getError());\n}\n\n';
                }
                str = (strP.length > 0 || strD.length > 0 ? '$params = create_params();\n' : '') + strP + strD;
                $('#params-code-panel').val(str);
            }

            /**
             * 生成radio或checkbox控件
             * @param {string} type 控件类型,如:radio,checkbox
             * @param {string} data 数据源,如:1=启动&2=暂停&!0=停止, 值前面加符号[!]表示选中
             * @param {string} field 表单域名称,即字段名称,如: name
             * @param {string} label 表单域描述,如: 名称
             * @param {string} required 是否必填项目, 如: required
             * @returns {string}
             * @since 1.0 2014-7-21 by sutroon
             */
            function generate_group_input(type, data, field, label, required) {
                if (!data) {
                    return '';
                }
                var arr = data.split('&'), item = '', str = '', checked = '';
                for (var i = 0; i < arr.length; i++) {
                    item = arr[i].split('=');
                    if (item[0][0] == '!') {
                        checked = ' checked="checked"';
                        item[0] = item[0].substr(1);
                    } else {
                        checked = '';
                    }
                    str += '<input type="' + type + '" name="' + field + '" value="' + item[0] + '" title="请选择' + label + '"' + checked + required + ' />' + item[1] + '\n';
                }
                return str;
            }

            /**
             * 生成option控件
             * @param {string} data 数据源,如:1=启动&2=暂停&!0=停止, 值前面加符号[!]表示选中
             * @returns {String}
             * @since 1.0 2014-7-21 by sutroon
             */
            function generate_group_option(data) {
                if (!data)
                    return '';
                var arr = data.split('&'), item = '', str = '', checked = '';
                for (var i = 0; i < arr.length; i++) {
                    item = arr[i].split('=');
                    checked = (item[0][0] == '!') ? ' selected="selected"' : '';
                    item[0] = item[0].substr(1);
                    str += '<option value="' + item[0] + '"' + checked + '>' + item[1] + '</option>';
                }
                return str;
            }
            /**
             * 表单UI构建器控件类型过滤方法
             
             * @param {jQueryObject} $tr
             * @returns {void}             
             * @since 1.0 2014-7-21 by sutroon
             */
            function formbuilder_typechange(type, $tr) {
                switch (type) {
                    case 'text':
                    case 'timepicker':
                    case 'datepicker':
                        $tr.find('input[name="jsonsource"]').parent().hide();
                        $tr.find('input[name="groupdata"]').parent().hide();
                        break;
                    case 'hidden':
                        $tr.find('input[name="label"]').parent().hide();
                        $tr.find('input[name="required"]').parent().hide();
                        $tr.find('input[name="groupdata"]').parent().hide();
                        $tr.find('input[name="groupdata"]').parent().hide();
                        break;
                    case 'select':
                        $tr.find('input[name="jsonsource"]').parent().show();
                        $tr.find('input[name="groupdata"]').parent().show();
                        break;
                    case 'radio':
                    case 'checkbox':
                        $tr.find('input[name="jsonsource"]').parent().hide();
                        $tr.find('input[name="groupdata"]').parent().show();
                        break;
                }
            }

            /**
             * 数据构建器类型过滤方法
             
             * @returns {void}             
             * @since 1.0 2014-7-23 by sutroon
             */
            function databuilder_typechange(type, $tr) {
                var $valuevar = $tr.find('input[name="valuevar"]');
                var $field = $tr.find('input[name="field"]');
                switch (type) {
                    case 'static':
                        if ($valuevar.val().indexOf('func_') > -1) {
                            $valuevar.val('');
                        }
                        $valuevar.attr('title', '字符或数值');
                        break;
                    case 'increment':
                        if ($valuevar.val().indexOf('func_inc') < 0) {
                            $valuevar.val('func_inc(1,1,' + $field.val() + ')');
                        }
                        $valuevar.attr('title', '格式为：func_inc(起始数值,步长,变量名),如: func_inc(1,2,field1)');
                        break;
                    case 'random':
                        if ($valuevar.val().indexOf('func_rnd') < 0) {
                            $valuevar.val('func_rnd(1-10)');
                        }
                        $valuevar.attr('title', '格式为：func_rnd(下限值,上限值+1)或func_rnd(值1,值2...值n),如: func_rnd(1-10),func(a,b,c,d,e,f)');
                        break;
                }
            }

            /**
             * 页面控制-切换构建器标签
             * @returns {void}
             * @since 
             *  1.1 2014-7-29 by sutroon 改进算法
             *  1.0 2014-7-21 by sutroon createdtime
             */
            function switch_tab($a) {
                var val = $a.attr('href');
                $a.addClass('cur').siblings().removeClass('cur');
                $('.tabcontent').hide();
                $('#' + val + '-builder').show();
            }
        </script>
        <script type="text/javascript" title="对象和通用方法">
            /**
             * 字典对象
             
             * @type Dictionary 
             * @since 1.0 2014-7-23 by sutroon
             * @example 
             *  var inc_dict=new Dictionary();
             */
            function Dictionary() {

                /**
                 * 键集合
                 */
                this.Keys = new Array();
                /**
                 * 值集合
                 */
                this.Values = new Array();
                /**
                 * 返回指定键名的值<br />
                 * 如果键名不存在则返回空字串
                 * 
                 * @param {string} key 键名称
                 * @returns {mixed}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example getByKey('key1');
                 */
                this.getByKey = function(key) {
                    var keyCount = this.Keys.length;
                    if (keyCount < 1) {
                        return '';
                    }
                    for (var i = 0; i < keyCount; i++)
                    {
                        if (this.Keys[i] == key)
                        {
                            return this.Values[i];
                        }
                    }
                    return '';
                };
                /**
                 * 返回指定索引的值<br />
                 * 如果索引不存在或溢出则返回空字串
                 * 
                 * @param {int} index 索引
                 * @returns {mixed}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example getByIndex(0);
                 */
                this.getByIndex = function(index) {
                    var keyCount = this.Keys.length;
                    if (keyCount < 1 || keyCount < index - 1) {
                        return '';
                    }
                    return this.Values[index];
                };
                /**
                 * 添加key和value
                 * @param {string} key 键名称
                 * @param {mixed} value 值
                 * @returns {Dictionary}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example add('key1','value1');
                 */
                this.add = function(key, value) {
                    var keyCount = this.Keys.length;
                    if (keyCount > 0)
                    {
                        var flag = true;
                        for (var i = 0; i < keyCount; i++)
                        {
                            if (this.Keys[i] == key)
                            {
                                flag = false;
                                break;
                                // 如果存在则不添加
                            }
                        }
                        if (flag)
                        {
                            this.Keys.push(key)
                            this.Values.push(value);
                        }
                    }
                    else
                    {
                        this.Keys.push(key)
                        this.Values.push(value);
                    }
                    return this;
                };
                /**
                 * 更改key和value
                 * @param {string} key 键名称
                 * @returns {Dictionary}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example update('key1','value1');
                 */
                this.update = function(key, value)
                {
                    var keyCount = this.Keys.length;
                    if (keyCount > 0)
                    {
                        var flag = -1;
                        for (var i = 0; i < keyCount; i++)
                        {
                            if (this.Keys[i] == key)
                            {
                                flag = i;
                                break;
                                // 查找相应的index
                            }
                        }
                        if (flag > -1)
                        {
                            this.Keys[flag] = key;
                            this.Values[flag] = value;
                        }
                        return this;
                    }
                    else
                    {
                        return this;
                    }
                };
                /**
                 * 移除key和value
                 * @param {string} key 键名称
                 * @returns {Dictionary}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example delete('key1');
                 */
                this.delete = function(key)
                {
                    var keyCount = this.Keys.length;
                    if (keyCount > 0)
                    {
                        var flag = -1;
                        for (var i = 0; i < keyCount; i++)
                        {
                            if (this.Keys[i] == key)
                            {
                                flag = i;
                                break;
                                // 查找相应的index
                            }
                        }
                        if (flag > -1)
                        {
                            this.Keys.splice(flag, 1);
                            // 移除
                            this.Values.splice(flag, 1);
                            // 移除
                        }
                        return this;
                    }
                    else
                    {
                        return this;
                    }
                };
                /**
                 * 检查键名称是否存在
                 * @param {string} key 键名称
                 * @returns {Boolean}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example keyExists('key1');
                 */
                this.keyExists = function(key)
                {
                    var keyCount = this.Keys.length;
                    if (keyCount == 0) {
                        return false;
                    }
                    for (var i = 0; i < keyCount; i++)
                    {
                        if (this.Keys[i] == key)
                        {
                            return true;
                        }
                    }
                    return false;
                };

                /**
                 * 清空所有项目
                 * @returns {void}
                 * @since 1.0 2014-7-24 by sutroon
                 */
                this.clear = function() {
                    this.Keys.splice(0);
                    this.Values.splice(0);
                }

                /**
                 * 获取Key字符串, 用符号拼接
                 * @param {string} separator 拼接符号
                 * @returns {string}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example toKeysString('&');
                 */
                this.toKeysString = function(separator)
                {
                    var keyCount = this.Keys.length;
                    if (keyCount > 0)
                    {
                        return this.Keys.join(separator);
                    }
                    else
                    {
                        return '';
                    }
                };
                /**
                 * 获取Value字符串, 用符号拼接
                 * @param {string} separator 拼接符号
                 * @returns {string}
                 * @since 1.0 2014-7-23 by sutroon
                 * @example toValuesString('&');
                 */
                this.toValuesString = function(separator)
                {
                    var keyCount = this.Keys.length;
                    if (keyCount > 0)
                    {
                        return this.Values.join(separator);
                    }
                    else
                    {
                        return '';
                    }
                }
            }

            /**
             * 解析函数模板并返回随机数
             * @param {string} tpl 函数模板,如:func_rnd(2-10),func_rnd(1,3,5,10,15),默认func_rnd(1,10)
             * @returns {int} 返回范围内的随机数,默认返回1到9之间的随机数
             * @since 1.0 2014-7-23 by sutroon 佩服自己哈!
             * @example 
             * 1.返回包含[下限值]和[上限值-1]之间的数值,下限值和上限值之间用横杠[-]隔开
             *      get_random_num('func_rnd(2-10)'): 5,6,11,3,7,6,8,10,2,9 返回包含下限2至上限9之间的随机数
             *      get_random_num(): 5,9,8,1,2,3,2,3,1,7 默认返回包含下线1至上限9之间的随机数
             * 2.返回指定范围值之间的随机值,范围值可以是数字或字符,范围值之间用逗号隔开
             *      get_random_num('func_rnd(1,3,5,10,15)'): 3,5,5,3,3,3,3,3,5,5 返回指定数值范围内的随机数值
             *      get_random_num('func_rnd(a,b,c,d,e)'): c,c,b,c,a,b,a,e,b,a 
             */
            function get_random_num(tpl) {
                if (tpl == undefined || tpl.length < 9) {
                    tpl = 'func_rnd(1-9)';
                }
                var para = tpl.substring(tpl.indexOf('(') + 1);
                para = para.substring(0, para.length - 1);
                if (para.indexOf('-') > -1) {
                    var arr = para.split('-');
                    return arr[0] * 1 + Math.round(Math.random() * (arr[1] - arr[0]));
                } else {
                    var arr = para.split(',');
                    return arr[Math.floor(Math.random() * arr.length)];
                }
            }
            var inc_dict = new Dictionary();
            /**
             * 返回自增长数值
             * @param {string} name 变量名称,必需声明,用于区分不同变量之间的自增长数值
             * @param {string} tpl 函数模板,如:func_inc(1,1),func_inc(100,5),默认func_inc(1,1)
             * @returns {int} 返回自增长数值,默认返回从1开始步长为1的数值
             * @since 1.0 2014-7-23 by sutroon 佩服自己哈!
             * @example
             *  var inc_dict=new Dictionary(); // 使用前必需在全局声明一个名称为inc_dict的实例!
             *  get_increment_num('func_inc()'): 1,2,3,4,5,6,7,8,9,10
             *  get_increment_num('func_inc(value1)'): 1,2,3,4,5,6,7,8,9,10
             *  get_increment_num('func_inc(1,1,value2)'): 1,2,3,4,5,6,7,8,9,10
             *  get_increment_num('func_inc(100,5,value3)'): 100,105,110,115,120,125,130,135,140,145
             */
            function get_increment_num(tpl) {
                if (tpl == undefined || tpl.length < 9) {
                    tpl = 'func_inc(1,1,incval)';
                }
                var para = tpl.substring(tpl.indexOf('(') + 1);
                para = para.substring(0, para.length - 1);

                var start = 1;
                var step = 1;
                var name = 'incval';
                if (para.length > 0) {
                    if (para.indexOf(',') > -1) {
                        var arr = para.split(',');
                        if (arr.length > 1) {
                            start = arr[0] * 1;
                            step = arr[1] * 1;
                        }
                        if (arr.length > 2) {
                            name = arr[2];
                        }
                    } else {
                        // func_inc(value1); 只传变量名
                        // func_inc(3); 只传步长
                        if (isNaN(para)) {
                            step = para * 1;
                        } else {
                            name = para;
                        }
                    }
                }
                var v = 0;
                if (inc_dict.keyExists(name)) {
                    v = inc_dict.getByKey(name) * 1;
                    v = v + step;
                    inc_dict.update(name, v);
                } else {
                    v = start;
                    inc_dict.add(name, v);
                }
                return v;
            }

            /**
             * 替换函数模板为具体值
             * @returns {string}
             * @since 1.0 2014-7-24 by sutroon
             * @example 
             *  var str = '', strF = 'id,a,b,c,d,e', strV = "'func_inc()','func_inc(5,1,vf1)','func_rnd()','func_rnd(1,5,10,15)','func_rnd(100-200)'";
             *  var inc_dict;
             *  for (var i = 0; i < 10; i++) {
             *      str += 'insert into (' + strF + ') values (' + replace_tpl_to_num(replace_tpl_to_num(strV, 'rnd'), 'inc') + ');\n';
             *  }
             *  alert(str);
             */
            function replace_tpl_to_num(tpls) {
                if (tpls == undefined || tpls.length == 0) {
                    return tpls;
                }
                var result = tpls.match(/func_inc\([^\)]*\)/g);
                if (result)
                {
                    for (var i = 0; i < result.length; i++)
                    {
                        tpls = tpls.replace(result[i], get_increment_num(result[i]));
                    }
                }
                result = tpls.match(/func_rnd\([^\)]*\)/g);
                if (result)
                {
                    for (var i = 0; i < result.length; i++)
                    {
                        tpls = tpls.replace(result[i], get_random_num(result[i]));
                    }
                }
                return tpls;
            }
        </script>
    </body>
</html>


